<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     pagizer
 * @subpackage  website
 */

/**
 * Generic gallery block
 */
class m_medias_actions_block_front_GalleryAction extends m_backoffice_extends_FrontAction
{
	public function execute()
	{
        $pageService = m_website_services_PageService::getInstance();
        $blockParams = $this->getBlockContext()->getParameters();
        $suffix = $this->getRequestParameter("urlSuffix");

        $docProvider = $this->getDocumentProvider();

        //if we have no parameters in the block and in the url, we take the first media folder.
        if(!isset($blockParams['folder']))
        {
            $rootId = m_backoffice_services_RootNodeService::getInstance()->getModuleRootNode("medias")->getUniqueId();
            $folder = $docProvider->loadDocuments("modules_backoffice/folder")->isChildOf($rootId)->retrieveFirstDocument($blockParams['blockLang']);
            
            if(is_null($folder))
            {
                return $this->setView($blockParams['view']);
            }

        }
        else
        {
            $folder = $docProvider->getByUniqueId($blockParams['folder'], $blockParams['blockLang']);
        }

        if(isset($suffix['model']) && $suffix['model'] == "medias/media")
        {
            $mediaTemp = $docProvider->loadDocuments("modules_medias/media")
                                                    ->isChildOf($folder->getId(), 'media')
                                                    ->whereIsEqual("title",  $suffix['url'])
                                                    ->retrieveFirstDocument();

            $folder = !is_null($mediaTemp) ? $mediaTemp : $folder;
        }

        $parentFolder = $folder->getDocumentParent();

        if(is_null($parentFolder)) return '';

        if($folder->getDocumentModel() == "modules_medias/media")
        {
            $medias = array($folder);
            $order = f_relation_Manager::getInstance()->getOrderNumber($parentFolder, $medias[0], "media", $medias[0]->getLang());

            $medias[] = $this->getNeighborsMedias($parentFolder, "previous", $order);
            $medias[] = $this->getNeighborsMedias($parentFolder, "next", $order);

            $this->addToModel('media', $medias[0]);
            $this->addToModel('medias', $medias);
            $this->setView('detail');
        }
        else
        {
            //check if the dynamic url is correct.
            if(!is_null($suffix))
            {
                $label = method_exists($folder, "getTitle") ? $folder->getTitle() : $folder->getLabel();
                $fLabel = f_core_Routing::formatStringForUrl($label, true);
                //die(var_dump($suffix));
            }

            if(is_null($parameters))
            {
                $this->generateThumb($folder);
            }

            $folders = $this->getDocuments($folder, "modules_backoffice/folder");

            $numPage = isset($parameters[2]) ? $parameters[2] : '1';
            $nbPicture = isset($blockParams['nbPicture']) && $blockParams['nbPicture'] != '0' ? intval($blockParams['nbPicture']) : null;
            $nbPictureTot = $this->getDocuments($folder, "modules_medias/media", null, null, true);
            $this->getPagination($folder, $numPage, $nbPicture, $nbPictureTot);

            $medias = $this->getDocuments($folder, "modules_medias/media", $nbPicture, $numPage);

            //Get all children folders and set the parameters to the modal
            if(!is_null($folders) && !empty($folders) && $blockParams['displaySubGal'])
            {
                $foldersTab = Array();

                /* @var $folder m_backoffice_documents_folder */
                foreach($folders as $folder)
                {
                    $folderTab = Array();
                    $folderTab["folder"] = $folder;
                    $folderTab["media"] = $this->getFolderPicture($folder);
                    $folderTab["url"] = $pageService->getDynamicUrl($folder);

                    if(!empty($folderTab["media"]))
                    {
                        $foldersTab[] = $folderTab;
                    }
                }

                if(!empty($foldersTab))
                {
                    $this->addToModel("folders", $foldersTab);
                }
            }

            //Get all children mdias and set the parameters to the modal
            if(!is_null($medias) && !empty($medias))
            {
                $mediasTab = Array();

                /* @var $media m_medias_documents_media */
                foreach($medias as $media)
                {
                    $mediaTab = Array();
                    $mediaTab["media"] = $media;
                    if($blockParams['details'])
                    {
                        $mediaTab["url"] = $pageService->getDynamicUrl($media, null, array("url" => $media->getTitle()));
                    }

                    $mediasTab[] = $mediaTab;
                }

                if(!empty($mediasTab))
                {
                    $this->addToModel("medias", $mediasTab);
                }
            }

            $this->setView($blockParams['view']);
        }

        if(!is_null($parameters))
        {
            $page = $this->getContext("currentPage")->setMetaTitle($folder->getLabel());
            $this->updateContext("frontOffice", $page);

            $url = $parentFolder->getUniqueId() == $rootFolder ? $page->getCompleteUrl() : $pageService->getDynamicUrl($parentFolder);

            if($blockParams['displaySubGal'] == 1)
            {
                $this->addToModel("returnUrl", $url);
            }
        }

        $this->addToModel("parentFolder", $parentFolder);
        $this->addToModel("blockParams", $blockParams);
	}

    private function getDocuments($parentDoc, $documentModel, $nbDoc = null, $numPage = null, $nb = false)
    {        
        $documents = $this->getDocumentProvider()
                        ->loadDocuments($documentModel)
                        ->byPublicationStatus("PUBLISHED")
                        ->isChildOf($parentDoc->getUniqueId(), null, true)
                        ->addAscOrder("relation_order");

        if($documentModel == "modules_medias/media")
        {
            $documents->whereLike("mime", "%image/%");
        }

        if(!$nb && !is_null($nbDoc) && !is_null($numPage))
        {
            $numPage = $nbDoc*($numPage-1);
            $numPage = ($numPage < 0) ? 0 : $numPage;

            $documents->limit($nbDoc, $numPage);
        }
        
        $documents = $nb ? $documents->count($parentDoc->getLang()) : $documents->retrieveDocuments($parentDoc->getLang());

        return $documents;
    }

    private function getFolderPicture($folder)
	{
		$tab = Array();
        $medias = Array();

		$folderChilds = f_relation_Manager::getInstance()->getChildsByDocTypeRecursive($folder->getUniqueId(), $folder->getDocumentModel(), $folder->getLang());
        $folderChilds[] = $folder;
        
		if(!is_null($folderChilds))
		{
			foreach($folderChilds as $folderChild)
			{
                $mediasChild = $this->getDocuments($folderChild, "modules_medias/media");
                $medias = array_merge($medias, $mediasChild);
			}
		}

		if(!empty($medias))
		{
            $nbTot = count($medias);
			$nb = rand(0, $nbTot-1);
			$media = $medias[$nb];
            $tab['media'] = $media;
            $tab['nb'] = $nbTot;
		}

		return $tab;
	}

    /**
     * Generate thumbnails and formats from the parameters of the block.
     * @param <type> $folder
     */
    private function generateThumb($folder)
    {
        $paramService = m_medias_services_ParameterService::getInstance();
        $parameters = $paramService->getParametersByFolderId($folder->getUniqueId(), $folder->getLang());

        $width = $this->getBlockParameter("picWidth");
        $height = $this->getBlockParameter("picHeight");
        $ok = true;

        if(!empty($parameters))
        {
            foreach($parameters as $parameter)
            {
                if($parameter->getWidth() == $width && $parameter->getHeight() == $height)
                {
                    $ok = false;
                    break;
                }
            }
        }

        if($ok)
        {
            $parameter = m_medias_documents_Parameter::createNew();
            $parameter	->setWidth($width)
                        ->setHeight($height)
                        ->setFolderId($folder->getUniqueId())
                        ->setGenerateOnUpload(1)
                        ->setCrop(4)
                        ->setLabel("GeneratedByGalleryBlock")
                        ->save();

            $folder->addParameter($parameter)->save();

            $folders = f_relation_Manager::getInstance()->getChildsByDocTypeRecursive($folder->getUniqueId(), $folder->getDocumentModel(), $folder->getLang());
            $folders[] = $folder;

            foreach($folders as $folder)
            {
                $medias = $folder->getMedia();

                if(!empty($medias))
                {
                    foreach($medias as $media)
                    {
                        $media->advancedResizePicture($parameter->getWidth(), $parameter->getHeight(), $parameter->getCrop());
                    }
                }
            }
        }
    }

    /**
     * Get next or previous media
     * @param <type> $media
     * @param <type> $attribute (next)
     */
    private function getNeighborsMedias($folder, $attribute, $orderNumber)
    {
        $methodWhere = $attribute == "next" ? "whereIsMoreThan" : "whereIsLessThan";
        $methodSort = $attribute == "next" ? "addAscOrder" : "addDescOrder";

        $media = $this->getDocumentProvider()
                        ->loadDocuments("modules_medias/media")
                        ->isChildOf($folder->getUniqueId(), "media", true)
                        ->$methodWhere("relation_order", $orderNumber)
                        ->$methodSort("relation_order")
                        ->byPublicationStatus("PUBLISHED")
                        ->retrieveFirstDocument($folder->getLang());
                        
        if(!is_null($media))
        {
            $url = m_website_services_PageService::getInstance()->getDynamicUrl($media, null, array("url" => $media->getTitle()));
            $media = array("document" => $media, "url" => $url);
            
            return $media;
        }

        return null;
    }
}